<template  #header>
  <el-tabs type="border-card" v-model="activeName" :before-leave="changeTab">
    <el-tab-pane label="客户信息" name="customerManage">
      <template>
        <div class="card-header">
          <span>客户信息列表</span>
        </div>
      </template>
      <el-row :gutter="10">
         <el-input placeholder="搜索姓名或手机或区域"   style="width: 180px;margin-right:10px;" v-model="searchContent" ></el-input> 
        
          <el-button  type="primary" size="small" @click="handlerSearch">搜索</el-button>
          <el-button size="small" type="primary" @click="showAddCustomerDialog">添加</el-button>
           <el-upload style="width:60px;float:right;margin-left:10px;"
              class="upload-demo"
             :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="handleBeforeUpload"
              :headers="headers"
              accept=".xls,.xlsx" >
            
              <el-button   type="primary">导入</el-button>
            </el-upload>
         
      </el-row>
      <el-table
        :data="tableData"
        style="width: 100%"
        highlight-current-row
        row-key="id"
        @row-dblclick="showVisit"
        @current-change="currentRowSelect"
      >
        <el-table-column prop="name" label="名称">
          <template #default="scope">
            <i
              class="el-icon-s-flag"
              style="color: red"
              v-if="scope.row.isFlag"
            ></i>
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column prop="phone" label="手机" />
        <el-table-column prop="ownArea" label="所属区域" />
        <el-table-column prop="connetState" label="联系状态">
          <template #default="scope">
            <el-tag v-if="scope.row.connetState == 0">{{
              connetStates[scope.row.connetState].label
            }}</el-tag>
            <el-tag type="warning" v-else-if="scope.row.connetState == 1">{{
              connetStates[scope.row.connetState].label
            }}</el-tag>
            <el-tag type="success" v-else-if="scope.row.connetState == 2">{{
              connetStates[scope.row.connetState].label
            }}</el-tag>
            <el-tag type="danger" v-else>{{
              connetStates[scope.row.connetState].label
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fromType" label="客户类型">
          <template #default="scope">
            {{ scope.row.fromType == 0 ? "直销" : "经销商销售" }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="adminName" label="所属销售" /> -->
        <el-table-column prop="remark" label="备注" />
        <!-- <el-table-column prop="dealerName" label="经销商" /> -->
        <!-- <el-table-column prop="idcard" label="身份证" /> -->
        <el-table-column prop="address" label="详细地址" />
         <el-table-column prop="shiftEndDate" label="截止日期" />
        <!-- <el-table-column prop="createAdminName" label="创建人" />
        <el-table-column prop="createDate" label="创建时间" /> -->
        <el-table-column label="操作" width="170">
          <template #default="scope">
             <el-tooltip content="编辑" placement="top">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              circle
              @click="handleEdit(scope.$index, scope.row)"
            ></el-button></el-tooltip>
             <el-tooltip content="删除" placement="top">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              circle
              @click="handleDelete(scope.$index, scope.row)"
            ></el-button></el-tooltip>
             <el-tooltip content="标记" placement="top">
            <el-button
              type="warning"
              circle
              size="mini"
              
              @click="handleFlag(scope.row.id)"
              icon="el-icon-s-flag"
            ></el-button></el-tooltip>
            <el-tooltip content="递延" placement="top" v-if="scope.row.isShift ===true">
            <el-button
                type="primary"
                circle
                size="mini"
                 
                @click="handleDelay(scope.row.id,scope.row.shiftEndDate)"
                icon="el-icon-s-promotion"
              ></el-button>
          </el-tooltip>
            
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="float: right; margin-top: 10px"
        :currentPage="currentPage"
        :page-size="10"
        :page-sizes="[10, 20, 100, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
      <CustomerAdd
        :centerDialogVisible="centerDialogVisible"
        @onCloseDialog="closeDialogVisible()"
      ></CustomerAdd>
      <CustomerEdit
        v-if="editDialogVisible === true"
        :customerId="id"
        :editDialogVisible="editDialogVisible"
        @onEditCloseDialog="closeEditDialogVisible"
      ></CustomerEdit>
      <!-- <CustomerShift
    v-if="shiftDialogVisible === true"
    :customerId="id"
    :shiftDialogVisible="shiftDialogVisible"
    @onShiftCloseDialog="closeShiftDialogVisible"
  ></CustomerShift> -->
    </el-tab-pane>
    <el-tab-pane label="回访信息" name="visitManage">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-button
            type="primary"
            style="margin-bottom: 10px"
            @click="handleVisit"
            >添加记录</el-button
          >
        </el-col>
      </el-row>
      <el-card>
        <el-timeline>
          <el-timeline-item
            :timestamp="visit.visitDate"
            v-for="(visit, index) in visitData"
            :key="index"
            placement="top"
          >
            <el-card>
              <p
                style="
                  display: block;
                  float: left;
                  height: 30px;
                  line-height: 30px;
                  margin-bottom: 20px;
                "
              >
                <el-tag v-if="visit.currentState == 0">{{
                  connetStates[visit.currentState].label
                }}</el-tag>
                <el-tag type="warning" v-else-if="visit.currentState == 1">{{
                  connetStates[visit.currentState].label
                }}</el-tag>
                <el-tag type="success" v-else-if="visit.currentState == 2">{{
                  connetStates[visit.currentState].label
                }}</el-tag>
                <el-tag type="danger" v-else>{{
                  connetStates[visit.currentState].label
                }}</el-tag>
                {{ visit.result }}
              </p>

              <p
                style="
                  display: block;
                  float: right;
                  height: 30px;
                  line-height: 30px;
                  margin-bottom: 20px;
                "
              >
                <!-- <el-button
              size="mini"
              @click="handleEditVisit(index, visit)"
              type="primary"
               icon="el-icon-edit" circle
              ></el-button> -->
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDeleteVisit(index, visit)"
                  icon="el-icon-delete"
                  circle
                ></el-button>
              </p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>
      <!-- <el-table :data="visitData" style="width: 100%">
        <el-table-column prop="customerName" label="客户" />
          <el-table-column prop="currentState" label="客户联系状态"  >
              <template #default="scope">
                <el-tag  v-if="scope.row.currentState==0">{{  connetStates[scope.row.currentState].label  }}</el-tag>
                <el-tag type="warning" v-else-if="scope.row.currentState==1">{{  connetStates[scope.row.currentState].label  }}</el-tag>
                 <el-tag type="success" v-else-if="scope.row.currentState==2">{{  connetStates[scope.row.currentState].label  }}</el-tag>
                  <el-tag type="danger" v-else>{{  connetStates[scope.row.currentState].label  }}</el-tag>
            </template>
        </el-table-column>
         <el-table-column prop="result" label="回访记录" />
        <el-table-column prop="adminName" label="操作人" />
         <el-table-column prop="visitDate" label="回访时间" />
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button
              size="mini"
              @click="handleEditVisit(scope.$index, scope.row)"
              type="primary"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDeleteVisit(scope.$index, scope.row)"
              >删除</el-button
            >
          
            
          </template>
        </el-table-column>
      </el-table> -->
      <AddVisit
        v-if="visitDialogVisible === true"
        :customerId="id"
        :currentState="currentState"
        :customerName="customerName"
        :visitDialogVisible="visitDialogVisible"
        @onCloseVisitVisible="closeVisitDialogVisible"
      ></AddVisit>
      <EditVisit
        v-if="visitEditDialogVisible === true"
        :visitId="visitId"
        :customerId="id"
        :currentState="currentState"
        :customerName="customerName"
        :visitEditDialogVisible="visitEditDialogVisible"
        @onCloseEditVisitVisible="closeEditVisitDialogVisible"
      ></EditVisit>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { reactive, toRefs, onMounted } from "vue";
import CustomerAdd from "@/components/cus/CustomerAdd.vue";
import CustomerEdit from "@/components/cus/CustomerEdit.vue";
import AddVisit from "../../components/cus/AddVisit.vue";
import EditVisit from "../../components/cus/EditVisit.vue";
// import CustomerShift from "@/components/customer/CustomerShift.vue";
import {
  useHandlerEdit,
  useHandleSizeChange,
  useHandleCurrentChange,
  useHandlerSearch,
  useDelete,
  loadData,
  getRequest,
  putRequest,
  deleteRequest,
  formatNowDate,
  getDateRegion 
} from "../../utils/api";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";

export default {
  name: "SysCustomer",
  components: {
    CustomerAdd,
    CustomerEdit,
    //     // CustomerShift,
    AddVisit,
    EditVisit,
  },

  setup(props, { emit }) {
    const baseUrl = "/sell/customer/";
    const state = reactive({
      connetStates: [
        {
          value: 0,
          label: "待沟通",
        },
        {
          value: 1,
          label: "沟通中",
        },
        {
          value: 2,
          label: "已下单",
        },
        {
          value: 3,
          label: "战败",
        },
      ],
      fromTypes: [
        {
          value: 0,
          label: "直销",
        },
        {
          value: 1,
          label: "经销商销售",
        },
      ],
      searchContent: "",
      tableData: [],
      visitData: [],
      centerDialogVisible: false,
      editDialogVisible: false,
      // shiftDialogVisible:false,
      visitDialogVisible: false,
      visitEditDialogVisible: false,
      total: 0,
      pageSize: 10,
      currentPage: 1,
      id: "",
      baseUrl,
      customerName: "",
      activeName: "customerManage",
      visitId: "",
      currentState: "",
      headers:{ Authorization: window.sessionStorage.getItem("tokenStr") },
     
      uploadUrl: '/sell/customer/import'
    });

    const showVisit = (row, column, event) => {
      state.activeName = "visitManage";
      state.id = row.id;
    };

    const loadVisitData = () => {
      getRequest("/sell/customer/rvisit/", { id: state.id }).then(
        (response) => {
          if (response) {
            state.visitData = response.data;
            // state.total = response.page.totalCount ;
          }
        }
      );
    };

    //处理标记信息 标记后数据会显示红旗 并且排在前面
    const handleFlag = (customerId) => {
      putRequest(`/sell/customer/status/${customerId}`).then((res) => {
        if (res) {
          loadData(state, state.baseUrl);
          ElMessage.success({
            type: "success",
            title: "成功",
            message: "操作成功",
            duration: 2000,
          });
        }
      });
    };

    const showAddCustomerDialog = () => {
      state.centerDialogVisible = true;
    };

    const closeDialogVisible = (visible, data) => {
      state.centerDialogVisible = false;
      loadData(state, state.baseUrl);
    };

    const closeEditDialogVisible = (visible, data) => {
      state.editDialogVisible = visible;

      if (data !== undefined) {
        loadData(state, state.baseUrl);
      }
    };
    // const closeShiftDialogVisible=(visible,data)=>{
    //   state.shiftDialogVisible = visible ;
    //   if(data!==undefined){
    //     loadData(state,state.baseUrl)
    //   }
    // }

    const closeVisitDialogVisible = (visible, data) => {
      state.visitDialogVisible = visible;
      if (data !== undefined) {
        loadVisitData();
      }
    };

    const closeEditVisitDialogVisible = (visible, data) => {
      state.visitEditDialogVisible = visible;
      if (data !== undefined) {
        loadVisitData();
      }
    };

    const handleEditVisit = (index, row) => {
      state.visitId = row.id;
      state.visitEditDialogVisible = true;
    };

    const handleDeleteVisit = (index, row) => {
      ElMessageBox.confirm("你确定要删除吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        callback: (action) => {
          if ("confirm" === action) {
            deleteRequest("/sell/customer/rvisit/", { id: row.id }).then(
              (response) => {
                if (response.code == 200) {
                  loadVisitData();
                  ElNotification({
                    type: "success",
                    title: "成功",
                    message: "删除成功",
                    duration: 2000,
                  });
                }
              },
              (error) => {
                ElNotification({
                  type: "error",
                  title: "失败",
                  message: "删除失败",
                  duration: 2000,
                });
              }
            );
          }
        },
      });
    };

    const handleDelay = (id,endDate)=>{
        var num = getDateRegion(endDate,formatNowDate())
      
        if(num>=7){
            ElMessage.error("7天以上，暂时不能递延")
            return ;
        }
        putRequest('/sell/customer/delay/'+id).then((res)=>{
          if(res){
              ElMessage.success(res.message)
          }else{
             ElMessage.error('操作失败！')
          }
         
        })
    }

    const currentChange = (pageNo) => {
      state.currentPage = pageNo;
      loadData(state, state.baseUrl);
    };
    // const handleChange=()=>{
    //     state.shiftDialogVisible = true ;
    // }
    const handleVisit = () => {
      state.visitDialogVisible = true;
    };

    const currentRowSelect = (currentRow, oldCurrentRow) => {
      state.id = currentRow.id;
      state.currentState = currentRow.connetState;
      state.customerName = currentRow.name;
      
    };

    // const tabSelect  = (r)=>{
    //    console.info(r.index)
    //    if(r===1){

    //       if(state.id){
    //           return true ;
    //       }else{
    //         return false ;
    //       }
    //    }
    // }

    const changeTab = (activeName, oldActiveName) => {
      return new Promise((resolve, reject) => {
        if (activeName == "visitManage") {
          if (state.id) {
            loadVisitData();
            return resolve();
          } else {
            ElMessage.error("请选中某一行客户信息数据！");
            return reject();
          }
        }
        return resolve();
      });
    };

   const handleAvatarSuccess = (res) => {
      ElMessage.success(res.message)
       loadData(state, state.baseUrl);
    };

    const handleBeforeUpload = (file) => {
     
      const name = file.name.split(".")[1];
      if (!["xls", "xlsx"].includes(name)) {
        ElMessage({
          showClose: true,
          message: "请上传Excel文件",
          type: "error",
        });
        return false;
      }

      return true;
    };

    onMounted(() => {
      loadData(state, state.baseUrl);
    });
    return {
      ...toRefs(state), //解构响应式数据
      ...useDelete(state, baseUrl),
      ...useHandlerSearch(state, baseUrl),
      ...useHandlerEdit(state),
      ...useHandleSizeChange(state, baseUrl),
      ...useHandleCurrentChange(state, baseUrl),
      handleAvatarSuccess,handleBeforeUpload,//文件上传
      showAddCustomerDialog,
      closeDialogVisible,
      closeEditDialogVisible,
      // closeShiftDialogVisible,
      currentChange,
      handleVisit,
      closeVisitDialogVisible,
      currentRowSelect,
      showVisit,
      //  tabSelect,
      changeTab,
      closeEditVisitDialogVisible,
      handleEditVisit,
      handleDeleteVisit,
      handleFlag,
      handleDelay //递延
    };
  },
};
</script>
<style scoped>
</style>